package com.cdtu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdtu.entity.Admin;
import com.cdtu.entity.OperationRecord;
import com.cdtu.entity.Resource;
import com.cdtu.service.AdminService;
import com.cdtu.service.OperationRecordService;
import com.cdtu.service.ResourceService;
import com.cdtu.vo.R;
import com.cdtu.vo.Result;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : Sakura
 * @Date : 2022/12/31 21:49
 */
@RestController
@RequestMapping("/resource")
//解决跨域问题
@CrossOrigin
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private OperationRecordService recordService;

    @Autowired
    private AdminService adminService;

    @GetMapping("/findAll")
    public List<Resource> queryResource(){

        List<Resource> list = resourceService.queryAll();
        return list;

    }


    @GetMapping("/findSimple")
    public Map<String,Object> findByPage(Integer pageNow,Integer pageSizes, String category){
        Map<String, Object> result=new HashMap<>();

        pageNow=pageNow==null?1:pageNow;
        pageSizes=pageSizes==null?8:pageSizes;

        List<Resource> resources = resourceService.findResourceByPage(pageNow, pageSizes, category);

        long total = resourceService.findResourceTotal(category);

        result.put("resources",resources);
        result.put("total",total);


        return result;
    }

    @GetMapping("/findByName")
    public Map<String,Object> findByName(Integer pageNow,Integer pageSize, String name, String category){
        Map<String, Object> result=new HashMap<>();
        System.out.println(category);

        pageNow=pageNow==null?1:pageNow;
        pageSize=pageSize==null?5:pageSize;

//
        List<Resource> resources = resourceService.list();
        long count = 0;
        if (!"".equals(category)&&!"".equals(name)){
            count = resources.stream().filter(resource -> resource.getCategory().contains(category))
                    .filter(resource -> resource.getName().contains(name)).count();
        }else if ("".equals(category)&&!"".equals(name)){
            count = resources.stream().filter(resource -> resource.getName().contains(name) ).count();
        }else if ("".equals(name)&&!"".equals(category)){
            count = resources.stream().filter(resource -> resource.getCategory().contains(category)).count();
        }

        if (!"".equals(category)){
            resources = resources.stream()
                    .filter(resource -> resource.getCategory().contains(category)).collect(Collectors.toList());
        }
        if (!"".equals(name)){
            resources = resources.stream()
                    .filter(resource -> resource.getName().contains(name)).collect(Collectors.toList());
        }
        int start=(pageNow-1)*pageSize;
        resources = resources.stream().skip(start).limit(pageSize).collect(Collectors.toList());
//
        result.put("resources",resources);
        result.put("total",count);
//
//
        return result;
    }
    /*public List<ResourceVO> queryResource(String category){

        //通过类型名称查询种类符合的条件，返回符合情况的集合
        List<Resource> list = resourceService.queryByCategory(category);
        return list;
    }*/

    @GetMapping("/delete")
    public Result deleteResource(String id){
        Result result=new Result();

        //根据id删除资源，
        int count = resourceService.deleteById(id);
        if (count<1){
            result.setStatus(false);
            result.setMsg("删除失败，请稍后再试");
            return result;
        }
        result.setMsg("删除成功");
        return result;
    }

    //这个方法既要添加物资，也要添加操作记录，事务的原子性
    @PostMapping("/add")
    @Transactional
    public Result add(@RequestBody Resource resource, String no, long adminId){
        Result result=new Result();
//        System.out.println(resource);
//        System.out.println("no:"+no);
        System.out.println(adminId);

        //判断是否为空字符串
        if ("".equals(resource.getName())&&"".equals(resource.getStock())&&""
                .equals(resource.getCategory())&&"undefined".equals(no)&&"".equals(no)
        ){
            result.setStatus(false);
            result.setMsg("添加失败，请填写正确信息");
            return result;
        }

        //判断是否为空
        if (resource.getName()==null&&resource.getCategory()==null&&resource.getName()==null){
            result.setStatus(false);
            result.setMsg("添加失败，请填写正确信息");
            return result;
        }

        String resName = resource.getName();

//        查找仓库中是否有这个药品
//        Resource oldResource = resourceService.findByName(resName);

        //仓库中有则直接添加数量
//        if (oldResource!=null){
//            int count = resourceService.addStockById(oldResource.getId(), resource.getStock());
//
//            //判断处理不成功的情况
//            if (count<1){
//                result.setStatus(false);
//                result.setMsg("添加失败，请重新添加");
//                return result;
//            }
//
//            //添加成功之后就新建操作记录对象
//            OperationRecord record =new OperationRecord();
//            record.setNo(no);
//            record.setResName(resName);
//            record.setCount(resource.getStock());
//            record.setCheckUser(1002);
//            record.setDate(new Date());
//
//            count = recordService.saveRecord(record);
//
//            if (count<1){
//                result.setStatus(false);
//                result.setMsg("添加失败，请重新尝试");
//                return result;
//            }
//
//            result.setMsg("添加成功");
//            return result;
//        }

        //仓库中没用就添加种类
        int count = resourceService.addResource(resource);

        if (count<1){
            result.setStatus(false);
            result.setMsg("添加失败，请重新添加");
            return result;
        }

        //添加成功之后就新建操作记录对象
        OperationRecord record =new OperationRecord();
        record.setNo(no);
        record.setResName(resName);
        record.setCount(resource.getStock());
        record.setCheckUser(adminId);

        record.setDate(new Date());
        record.setDetail("入库");
        record.setCategory(resource.getCategory());


        count = recordService.saveRecord(record);

        if (count<1){
            result.setStatus(false);
            result.setMsg("添加失败，请重新尝试");
            return result;
        }

        result.setMsg("添加成功");
        return result;
    }

    @PostMapping("/update")
    public Result update(@RequestBody Resource resource){
        Result result = new Result();

        //这里执行修改的业务
        boolean flag = resourceService.updateById(resource);

        if (!flag){
            result.setStatus(false);
            result.setMsg("修改失败，请稍后尝试");
            return result;
        }

        result.setMsg("修改成功");
        return result;
    }

    @GetMapping("/findByPage")
    public Map<String,Object> findByPage(Integer pageNow,Integer pageSizes){
        Map<String, Object> result=new HashMap<>();

        pageNow=pageNow==null?1:pageNow;
        pageSizes=pageSizes==null?8:pageSizes;

        List<Resource> resources = resourceService.findByPage(pageNow, pageSizes);

        long total = resourceService.findTotal();

        result.put("resources",resources);
        result.put("total",total);


        return result;
    }

    /**
     * 批量添加物资
     * @return
     */
    @Transactional
    @PostMapping("/importResource/{aid}")
    public R importResource(@PathVariable("aid") long aid , MultipartFile file){
        Admin admin = adminService.getById(1);
        int count = 0;
        try {
            InputStream inputStream = file.getInputStream();
//            XSSFWorkbook xssfWorkbook = new XSSFWorkbook("C:\\Users\\Sakura\\Desktop\\批量添加物资模板.csv");
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = xssfWorkbook.getSheetAt(0);

            int lastRowNum = sheet.getLastRowNum();
            for (int i = 1; i < lastRowNum + 1; i++) {
                XSSFRow row = sheet.getRow(i);
                if (row != null){
                    List<String> stringList = new ArrayList<>();
                    for (Cell cell : row) {
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String value = cell.getStringCellValue();
                        if (value == ""){
                            stringList.add(" ");
                        } else {
                            stringList.add(value);
                        }
                    }
                    if (stringList.size() > 2){
                        LambdaQueryWrapper<Resource> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(Resource::getId,stringList.get(0));
//                        Resource one = resourceService.getOne(queryWrapper);
//                        if (one == null){
                            Resource resource = new Resource();
                            resource.setName(stringList.get(1));
                            resource.setCategory(stringList.get(2));
                            resource.setStock(Integer.valueOf(stringList.get(3)));
//                            System.out.println(stringList.get(4));
//                            System.out.println(System.currentTimeMillis());
                            resource.setInvalidDate(new SimpleDateFormat("yyyy/MM/dd").parse(stringList.get(4)));
                            resource.setPower(stringList.get(5));
                            boolean result = resourceService.save(resource);
                            if (!result){
                                return R.error("第"+count+"行资源添加失败存在数据问题，后续资源添加终止");
                            }
//                            资源添加成功之后需要添加操作记录
                            OperationRecord record = new OperationRecord();
                            record.setNo(stringList.get(0));
                            record.setDetail("入库");
                            record.setResName(stringList.get(1));
                            record.setCategory(stringList.get(2));
                            record.setCount(Integer.valueOf(stringList.get(3)));
                            record.setDate(new Date());
                            record.setCheckUser(admin.getId());
                            result = recordService.save(record);
                        if (!result){
                            return R.error("第"+count+"行资源添加失败存在数据问题，后续资源添加终止");
                        }
//                        }
                        count++;
                    }
                }
            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
        return R.success("增加物资成功");
    }


//    @RequestMapping("/save")
//    public Result addUser(@RequestBody User user){
//        String uid = String.valueOf(user.getId());
//        User user1 = usersService.findById(uid);
//        Result result = new Result();
//
//        if (user1==null){
//            try {
//                usersService.save(user);
//                result.setMsg("用户保存成功");
//            }catch(Exception e){
//                result.setStatus(false);
//                result.setMsg("系统错误，保存用户信息的失败！！！！");
//            }
//        }else {
//            try {
//                usersService.updateById(user);
//                result.setMsg("用户信息修改成功");
//            }catch(Exception e){
//                result.setStatus(false);
//                result.setMsg("系统错误，修改用户信息的失败！！！！");
//            }
//
//        }
//        return result;
//    }

}
